package javabase.concurrency;

/**
 * @author fance
 * @date 2018/7/12 20:14
 */
public class WaitNotify {
    volatile static boolean flag = true;
    static Object lock = new Object();

    public static void main(String[] args) {
        Thread thread1 = new Thread(new Wait(),"wait...");
        thread1.start();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Thread thread2 = new Thread(new Notify(),"notify...");
        thread2.start();
    }

    static class Wait implements Runnable {
        @Override
        public void run() {
            synchronized (lock) {
                while (flag) {
                    System.out.println("flag is true wait ..." + System.currentTimeMillis());
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("over ...  flag is false");
            }
        }
    }
    static class Notify implements Runnable {
        @Override
        public void run() {
            synchronized (lock) {
                System.out.println("hold lock  notify ... " + System.currentTimeMillis());
               lock.notifyAll();
               flag = false;
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            synchronized (lock) {
                System.out.println("hold lock  again   ... " + System.currentTimeMillis());
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
